<template>
  <div class="cx-video">
    <div class="video-grid">
      <!-- 视频列表 -->
      <div 
        v-for="(video, index) in videoList" 
        :key="video.netId || index"
        class="video-item"
        @click="handleVideoClick(video)"
      >
        <!-- 视频封面或占位符 -->
        <img 
          v-if="video.coverUrl" 
          :src="video.coverUrl" 
          class="video-cover"
          alt="视频封面"
        />
        <div v-else class="video-placeholder">
          <i class="el-icon-video-play play-icon"></i>
        </div>
        
        <!-- 视频时长 -->
        <div v-if="video.duration" class="video-duration">
          {{ formatDuration(video.duration) }}
        </div>
        
        <!-- 上传进度 -->
        <div v-if="video.progress !== undefined && video.progress < 1" class="video-progress">
          <el-progress 
            type="circle" 
            :percentage="Math.round((video.progress || 0) * 100)"
            :width="60"
          />
          <span class="progress-text">{{ Math.round((video.progress || 0) * 100) }}%</span>
        </div>
        
        <!-- 操作遮罩 -->
        <div v-if="editable" class="video-mask">
          <div class="video-actions">
            <el-button 
              type="primary" 
              icon="el-icon-video-play" 
              circle 
              size="small"
              @click.stop="handleVideoClick(video)"
            />
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              circle 
              size="small"
              @click.stop="handleDelete(video)"
            />
          </div>
        </div>
      </div>
      
      <!-- 上传按钮 -->
      <div 
        v-if="editable"
        class="video-item upload-btn"
        @click="handleUpload"
      >
        <i class="el-icon-plus upload-icon"></i>
        <span class="upload-text">上传视频</span>
      </div>
    </div>
    
    <!-- 视频播放对话框 -->
    <el-dialog
      v-model:visible="showVideoDialog"
      :title="currentVideoTitle"
      width="800px"
      class="video-dialog"
      @close="handleDialogClose"
    >
      <video
        v-if="showVideoDialog"
        ref="videoPlayer"
        :src="currentVideoUrl"
        controls
        autoplay
        style="width: 100%; height: 450px;"
      ></video>
    </el-dialog>
    
    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept="video/*"
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script>
/**
 * 组件名称: Video (Element UI 版本)
 * 功能说明: 视频上传和查看组件
 * 研发时间: 2025/11/17
 * 研发人员: AI Assistant
 */

export default {
  name: 'Video',
  
  props: {
    editable: {
      type: Boolean,
      default: true
    },
    controller: {
      type: Object,
      required: true
    },
    busType: {
      type: String,
      default: '0'
    },
    maxDuration: {
      type: Number,
      default: 300
    },
    isCompress: {
      type: Boolean,
      default: false
    },
    saveGallery: {
      type: Boolean,
      default: false
    }
  },
  
  data() {
    return {
      videoList: [],
      showVideoDialog: false,
      currentVideoUrl: '',
      currentVideoTitle: '',
      uploadProgressListener: null
    }
  },
  
  computed: {
    currentVideoList() {
      if (this.controller && typeof this.controller.getVideoList === 'function') {
        return this.controller.getVideoList(this.busType)
      }
      return []
    }
  },
  
  created() {
    this.initComponent()
  },
  
  beforeUnmount() {
    if (this.controller && this.uploadProgressListener) {
      this.controller.removeUploadProgressListener(this.uploadProgressListener)
    }
  },
  
  methods: {
    initComponent() {
      this.updateVideoList()
      this.bindControllerEvents()
    },
    
    bindControllerEvents() {
      if (this.controller && typeof this.controller === 'object') {
        this.uploadProgressListener = (fileBean, progress) => {
          const videoIndex = this.videoList.findIndex(v => v.url === fileBean.url)
          if (videoIndex !== -1) {
            this.$set(this.videoList[videoIndex], 'progress', progress)
          }
        }
        
        if (typeof this.controller.addUploadProgressListener === 'function') {
          this.controller.addUploadProgressListener(this.uploadProgressListener)
        }
      }
    },
    
    updateVideoList() {
      const newVideoList = this.currentVideoList
      this.videoList = newVideoList.map(video => {
        const newVideo = { ...video }
        if (newVideo.progress === undefined) {
          this.$set(newVideo, 'progress', 1)
        }
        return newVideo
      })
    },
    
    handleUpload() {
      if (!this.editable) return
      this.$refs.fileInput.click()
    },
    
    async handleFileChange(event) {
      const file = event.target.files[0]
      if (!file) return
      
      await this.uploadSingleVideo(file)
      
      // 清空input
      event.target.value = ''
    },
    
    async uploadSingleVideo(file) {
      try {
        // 创建临时URL
        const tempUrl = URL.createObjectURL(file)
        
        // 获取视频时长
        const duration = await this.getVideoDuration(tempUrl)
        
        const title = typeof this.controller.getTitle === 'function'
          ? this.controller.getTitle({}, this.busType)
          : `video_${Date.now()}`
        
        const fileBean = {
          title: title || `video_${Date.now()}`,
          userRawTitle: !!title,
          url: tempUrl,
          file: file,
          busType: this.busType,
          mediaType: 'VIDEO',
          memo: this.controller.memo || '',
          task: this.controller.task || '',
          progress: 0,
          netId: 0,
          duration: duration
        }
        
        this.$set(fileBean, 'progress', 0)
        
        // 通过 controller 方法添加文件，避免直接修改 prop
        if (typeof this.controller.addFile === 'function') {
          this.controller.addFile(fileBean)
        } else {
          // 通过事件通知父组件
          this.$emit('file-add', fileBean)
        }
        
        this.updateVideoList()
        
        // 上传文件
        await this.controller.uploadFile(
          this.controller.entityId,
          fileBean,
          this.handleUploadSuccess,
          {}
        )
        
        this.$emit('upload-complete', fileBean)
      } catch (error) {
        this.$message.error('上传视频失败: ' + error.message)
        console.error('上传视频失败:', error)
      }
    },
    
    getVideoDuration(url) {
      return new Promise((resolve) => {
        const video = document.createElement('video')
        video.src = url
        video.onloadedmetadata = () => {
          resolve(video.duration)
        }
        video.onerror = () => {
          resolve(0)
        }
      })
    },
    
    handleVideoClick(video) {
      this.currentVideoUrl = video.url
      this.currentVideoTitle = video.title || '视频播放'
      this.showVideoDialog = true
      this.$emit('video-selected', video)
    },
    
    handleDialogClose() {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.pause()
      }
      this.currentVideoUrl = ''
      this.currentVideoTitle = ''
    },
    
    async handleDelete(video) {
      try {
        await this.$confirm('确定要删除这个视频吗？', '确认删除', {
          type: 'warning'
        })
        
        if (this.controller && typeof this.controller.delFile === 'function') {
          await this.controller.delFile(video, {})
          this.$emit('video-deleted', video)
          this.$message.success('删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + error.message)
        }
      }
    },
    
    formatDuration(seconds) {
      if (!seconds || seconds <= 0) return '00:00'
      
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = Math.floor(seconds % 60)
      
      if (hours > 0) {
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
      } else {
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
      }
    },
    
    handleUploadSuccess(result) {
      console.log('视频上传成功:', result)
    }
  }
}
</script>

<style lang="scss" scoped>
.cx-video {
  padding: 10px;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
}

.video-item {
  position: relative;
  width: 100%;
  aspect-ratio: 16/9;
  border-radius: 5px;
  overflow: hidden;
  background: #000;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.video-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
}

.play-icon {
  font-size: 48px;
  color: #fff;
}

.video-progress {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.progress-text {
  color: white;
  font-size: 12px;
  margin-top: 5px;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border: 2px dashed #dee2e6;
  border-radius: 5px;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    color: #409eff;
    background: #ecf5ff;
  }
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  font-size: 12px;
  border-radius: 3px;
}

.video-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  
  .video-item:hover & {
    opacity: 1;
  }
}

.video-actions {
  display: flex;
  gap: 10px;
}

.video-dialog {
  ::v-deep .el-dialog__body {
    padding: 0;
    background: #000;
  }
}
</style>
